package renguanyu.app.auth4fx.service.role;

import renguanyu.app.auth4fx.dao.role.RoleDao;
import renguanyu.app.auth4fx.model.Page;
import renguanyu.app.auth4fx.model.role.RoleDto;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RoleService {
    
    public static Page getRolePage(RoleDto roleDto){
        Page page = new Page();
        page.setPageCount(countRolePages(roleDto));
        page.setPageData(listRolesByPage(roleDto));
        return page;
    }

    public static Integer countRolePages(RoleDto roleDto) {
        String name = roleDto.getName();
        Integer pageSize = roleDto.getPageSize();
        Integer total = RoleDao.getRoleTotal(name);
        Integer totalPage = (total + pageSize - 1) / pageSize;
        return totalPage;
    }

    public static List<Map<String, Object>> listRolesByPage(RoleDto roleDto) {
        Integer pageSize = roleDto.getPageSize();
        Integer currentPageIndex = roleDto.getCurrentPageIndex();
        String name = roleDto.getName();
        Integer limit = pageSize;
        Integer offset = currentPageIndex * pageSize;
        return RoleDao.getPagedRoles(limit, offset, name);
    }

    public static Integer saveRole(RoleDto roleDto){
        String name = roleDto.getName();
        return RoleDao.saveRole(name);
    }

    public static Integer updateRole(RoleDto roleDto){
        String id = roleDto.getId();
        String name = roleDto.getName();
        return RoleDao.updateRole(name,id);
    }

    public static Integer deleteRole(RoleDto roleDto){
        List<String> ids = roleDto.getIds();
        String inSql = ids.stream().map(id -> "?").collect(Collectors.joining(","));
        return RoleDao.deleteRole(ids,inSql);
    }
}
